package com.akino.gulimall.search.thread;

import java.util.concurrent.*;

/**
 * @author Akino
 * @version 1.0
 */
public class ThreadTest {
    // 4.线程池（系统中只能有一两个池）
    public static ExecutorService execute = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
        }, execute);

    }

    public void thread(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 启动线程的几种方式
         */
        // 1.继承Thread
        Thread01 thread = new Thread01();
        thread.start();
        System.out.println("main...end...");
        // 2.实现Runnable接口
        Runnable01 runnable = new Runnable01();
        new Thread(runnable).start();
        System.out.println("main...end...");
        // 3.实现Callable接口+FutureTask（可以拿到返回结果，可以处理异常）
        FutureTask<Integer> futureTask = new FutureTask<>(new Callable());
        new Thread(futureTask).start();
        // 阻塞等待整个线程执行完成，获取返回结果
        Integer integer = futureTask.get();
        System.out.println("main...end..."+integer);
        // 4.线程池
        execute.execute(new Runnable01());
        /**
         * 业务代码中，1/2/3的启动线程方式都不用，将所有的多线程异步任务都交给线程池执行
         */
    }


    public static class Thread01 extends Thread{
        @Override
        public void run() {
            System.out.println("当前线程："+Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果："+i);
        }
    }
    public static class Runnable01 implements Runnable{
        @Override
        public void run() {
            System.out.println("当前线程："+Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果："+i);
        }
    }
    public static class Callable implements java.util.concurrent.Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程："+Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果："+i);
            return i;
        }
    }
}
